<?php
declare(strict_types=1);

namespace App\Wxc\Controller\SharerMp\V1;

use App\Wxc\Request\SharerMp\V1\GetSharerFormListRequest;
use App\Wxc\Request\SharerMp\V1\PostSharerFormRequest;
use App\Wxc\Service\Input\SharerFormInput;
use App\Wxc\Service\Query\SharerFormQuery;
use App\Wxc\Service\Query\ShopCfgQuery;
use App\Wxc\Service\WxcSharerFormService;
use App\Wxc\Service\WxcSharerMpService;
use App\Wxc\Service\WxcShopCfgService;
use Exception;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Mine\Annotation\Auth;
use Mine\Middlewares\CheckModuleMiddleware;
use Mine\MineController;
use Psr\Http\Message\ResponseInterface;

/**
 * 分享员接口
 */
#[Controller(prefix: "wxc/sharer-mp/v1/sharer"), Auth('wxc_sharer_mp')]
#[Middleware(middleware: CheckModuleMiddleware::class)]
class SharerController extends MineController
{
    #[Inject]
    protected WxcSharerFormService $formService;


    /**
     * 申请分享员
     */
    #[PostMapping('form')]
    public function postForm(): ResponseInterface
    {
        $req = PostSharerFormRequest::validateAndCreate($this->request->all());
        // 获取店铺信息
        $getShop = new ShopCfgQuery();
        $getShop->shop_id = $req->shop_id;
        $shop = container()->get(WxcShopCfgService::class)->queryOne($getShop);
        if (!$shop) {
            throw new Exception('店铺不存在');
        }

        $input = SharerFormInput::from($req);
        $input->app_id = $shop->app_id;
        $input->site_id = $shop->site_id;
        $input->openid = container()->get(WxcSharerMpService::class)->getUserInfo()['openid'] ?? '';
        $res = call_with_site($input->site_id, function () use ($input) {
            return $this->formService->add($input);
        });

        return $this->success('ok', $res);
    }

    /**
     * 分享员申请记录
     */
    #[GetMapping('form/list')]
    public function getFormList(): ResponseInterface
    {
        $req = GetSharerFormListRequest::validateAndCreate($this->request->all());
        $get = SharerFormQuery::from($req);
        $get->withRelation(['shopInfo']);
        return $this->success('ok', $this->formService->queryCursorPagination('form_id', $get, $req->next_key, $req->page_size));
    }
}
